package com.ruoyi.web.controller.scheduler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.hbs.domain.ApiConfig;
import com.ruoyi.hbs.mapper.ApiConfigMapper;
import com.ruoyi.hbs.mapper.HbsBusinessMappingMapper;
import com.ruoyi.hbs.mapper.HbsProductMappingMapper;
import com.ruoyi.hbs.mapper.HbsTerminalMappingMapper;
import com.ruoyi.hbs.service.SingleSalesInventoryRecordsService;
import com.ruoyi.web.service.impl.HbsDataSyncServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 简化药品销售与库存记录表定时拉取
 *
 * @author wl
 * @date 2025年11月04日16:34
 */
@Component
@Slf4j
public class SalesInventoryRecordsTask {
    @Autowired
    private SingleSalesInventoryRecordsService singleSalesInventoryRecordsService;

    @Autowired
    private HbsDataSyncServiceImpl hbsDataSyncService;

    @Autowired
    private ApiConfigMapper apiConfigMapper;
    @Autowired
    private HbsProductMappingMapper hbsProductMappingMapper;
    @Autowired
    private HbsBusinessMappingMapper hbsBusinessMappingMapper;
    @Autowired
    private HbsTerminalMappingMapper hbsTerminalMapping;

//    @Scheduled(cron = "0 0 * * * ?")
//    @Scheduled(cron = "0 */2 * * * ?")
//    @Scheduled(cron = "*/5 * * * * ?")
    /**
     *
     * 简化药品销售与库存记录表定时拉取同步
     */
//    @Scheduled(cron = "0 0 * * * ?")
    @SchedulerLock(name = "digitalEmpTaskScheduler", lockAtMostFor = "PT14M", lockAtLeastFor = "PT5M")
    public void singleSalesInventoryRecordsTask() {
        log.info("开始执行简化药品销售与库存记录表定时任务");
        singleSalesInventoryRecordsService.syncImport();
        log.info("结束执行简化药品销售与库存记录表定时任务");
    }




    /**
     * 每天9点零5分执行一次
     * 同步产品档案数据
     */
    @Scheduled(cron = "0 5 9 * * ?")
    @SchedulerLock(name = "syncProductArchiveTask", lockAtMostFor = "PT3M", lockAtLeastFor = "PT2M")
    public void syncProductArchiveTask() {
        log.info("开始执行同步产品档案数据定时同步任务");
        JSONObject bodyJson = getBodyJson("产品档案>主档");
        try {
            hbsDataSyncService.syncProductArchiveData(bodyJson);
            log.info("同步产品档案数据同步成功");
        } catch (Exception e) {
            log.error("同步产品档案数据同步失败: ", e);
        }
    }

    /**
     * 每天9点零7分执行一次
     * 定期同步同步商业档案数据
     */
    @Scheduled(cron = "0 7 9 * * ?")
    @SchedulerLock(name = "syncBusinessArchiveTask", lockAtMostFor = "PT3M", lockAtLeastFor = "PT2M")
    public void syncBusinessArchiveTask() {
        long startTime = System.currentTimeMillis();
        log.info("开始执行同步商业档案数据定时同步任务，开始时间: {}", new Date(startTime));
        JSONObject bodyJson = getBodyJson("商业档案>主档");
        try {
            hbsDataSyncService.syncBusinessArchiveData(bodyJson);
            long endTime = System.currentTimeMillis();
            log.info("同步商业档案数据同步完成，结束时间: {}，耗时: {}ms", new Date(endTime), endTime - startTime);
        } catch (Exception e) {
            log.error("同步商业档案数据同步失败: ", e);
        }
    }


    /**
     * 每天9点零3分执行一次
     * 定期同步终端档案数据
     */
    @Scheduled(cron = "0 3 9 * * ?")
    @SchedulerLock(name = "syncTerminalArchiveTask", lockAtMostFor = "PT3M", lockAtLeastFor = "PT2M")
    public void syncTerminalArchiveTask() {
        long startTime = System.currentTimeMillis();
        log.info("开始执行同步终端档案数据定时同步任务，开始时间: {}", new Date(startTime));
        JSONObject bodyJson = getBodyJson("终端档案>主档");
        try {
            hbsDataSyncService.syncTerminalArchiveData(bodyJson);
            long endTime = System.currentTimeMillis();
            log.info("同步终端档案数据同步完成，结束时间: {}，耗时: {}ms", new Date(endTime), endTime - startTime);
        } catch (Exception e) {
            log.error("同步终端档案数据同步失败: ", e);
        }
    }


//    /**
//     * 每小时执行一次数据匹配任务
//     */
////    @Scheduled(cron = "0 0 * * * ?")
//    @SchedulerLock(name = "dataMatchingTask", lockAtMostFor = "PT10M", lockAtLeastFor = "PT5M")
//    public void executeDataMatching() {
//        long startTime = System.currentTimeMillis();
//        log.info("开始执行数据匹配定时任务，开始时间: {}", new Date(startTime));
//        try {
//            singleSalesInventoryRecordsService.processUnmatchedRecords();
//            long endTime = System.currentTimeMillis();
//            log.info("数据匹配定时任务执行完成，结束时间: {}，耗时: {}ms", new Date(endTime), endTime - startTime);
//            log.info("开始处理终端首单记录");
//            singleSalesInventoryRecordsService.msfxProcessTerminalFirstOrder();
//            log.info("结束处理终端首单记录");
//        } catch (Exception e) {
//            long endTime = System.currentTimeMillis();
//            log.error("数据匹配定时任务执行失败，结束时间: {}，耗时: {}ms", new Date(endTime), endTime - startTime, e);
//        }
//    }


    /**
     * 获取同步参数
     *
     * @param tableConfigName
     * @return
     */
    private JSONObject getBodyJson(String tableConfigName) {
        // 构造同步参数
        JSONObject bodyJson = new JSONObject();
        ApiConfig apiConfig = apiConfigMapper.selectOne(new LambdaQueryWrapper<ApiConfig>().eq(ApiConfig::getSpaceName, "DHY业务链"));
        bodyJson.set("space_id", apiConfig.getSpaceId());
        bodyJson.set("tableConfigName", tableConfigName);

        // 设置时间范围过滤条件
        JSONObject filter = new JSONObject();
        JSONArray andArray = new JSONArray();

        // 开始时间：昨天早上九点
        String startTime = getYesterdayMorning9am();
        JSONObject startCondition = new JSONObject();
        startCondition.set("field", "created_on");
        JSONObject startQuery = new JSONObject();
        startQuery.set("gte", startTime);
        startCondition.set("query", startQuery);
        andArray.add(startCondition);

        // 结束时间：当前时间
        String endTime = getCurrentTime();
        JSONObject endCondition = new JSONObject();
        endCondition.set("field", "created_on");
        JSONObject endQuery = new JSONObject();
        endQuery.set("lte", endTime);
        endCondition.set("query", endQuery);
        andArray.add(endCondition);

        filter.set("and", andArray);
        bodyJson.set("filter", filter);
        return bodyJson;
    }

    /**
     * 获取昨天早上九点的时间字符串
     */
    private String getYesterdayMorning9am() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1); // 昨天
        calendar.set(Calendar.HOUR_OF_DAY, 9); // 早上九点
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
    }

    /**
     * 获取当前时间字符串
     */
    private String getCurrentTime() {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    }
}
